package ltd.ninefish.framework.core.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author zhaoxiubin
 * create-time 2024-01-20 19:15
 * description 错误信息处理类
 **/

public class ExceptionUtils {
    /**
     * 获取exception的详细错误信息。
     *
     */
    public static String getExceptionMessage(Throwable e)
    {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }

    /**
     *  获取exception的详细错误信息。
     * @param e
     * @return
     */
    public static String getExceptionMessage(Exception e)
    {
        Throwable root = ExceptionUtil.getRootCause(e);
        root = (root == null ? e : root);
        if (root == null)
        {
            return StrUtil.EMPTY;
        }
        return getExceptionMessage(root);
    }

    /**
     * 获取根异常信息。
     *
     * @param e 异常
     * @return
     */
    public static String getRootErrorMessage(Exception e)
    {
        Throwable root = ExceptionUtil.getRootCause(e);
        root = (root == null ? e : root);
        if (root == null)
        {
            return StrUtil.EMPTY;
        }
        String msg = root.getMessage();
        if (msg == null)
        {
            return "null";
        }
        return StrUtil.emptyToDefault(msg, StrUtil.EMPTY);
    }
}
